//
//  WHBaseViewVC.swift
//  ttjx
//
//  Created by 文 on 2019/8/28.
//  Copyright © 2019 ttjx. All rights reserved.
//

import UIKit
import SnapKit
import MCToast

let kFitWidth: (CGFloat) -> CGFloat = { width in
    return width * kScreenWidth / 375.0
}

class WHBaseViewVC: ViewController {
    
    public var fatherViewController: UIViewController?
    
    var navigationView = UIView()
    var naviTitleLabel     = UILabel()
    var naviBackImg        = UIImageView()
    
    let scrollView : UIScrollView = {
        let scro = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDHT, height: SCREEN_HEIGHT))
        scro.backgroundColor = .COLOR_LIGHT_GREY
        if #available(iOS 11.0, *) {
            scro.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        scro.bounces = true
        
        return scro
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        
        self.view.isUserInteractionEnabled = true
        
        if #available(iOS 13.0, *) {
            self.overrideUserInterfaceStyle = .light
        } else {
            // Fallback on earlier versions
        }
    }
    
     override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        //print("viewWillLayoutSubviews：\(self.tabBarController?.tabBar.subviews)")
        let aClass:AnyClass = NSClassFromString("UITabBarButton")!
        guard let views = self.tabBarController?.tabBar.subviews else { return }
        for view in views {
            if view.isKind(of: aClass) {
                view.removeFromSuperview()
            }
        }
    }
    
    func initNavigationView(){
       self.view.addSubview(navigationView)
        navigationView.backgroundColor = UIColor.white
       navigationView.snp.makeConstraints { (frame) in
           frame.width.equalTo(SCREEN_WIDHT)
           frame.height.equalTo(getNavigationBarHeight())
           frame.left.equalTo(0)
           frame.top.equalTo(0)
       }
        
        navigationView.addSubview(naviTitleLabel)
        naviTitleLabel.textColor = WHColor_TextBlack()
        naviTitleLabel.font = UIFont.systemFont(ofSize: 15)
        naviTitleLabel.textAlignment = NSTextAlignment.center
        naviTitleLabel.snp.makeConstraints { (frame) in
            frame.width.equalTo(SCREEN_WIDHT)
            frame.height.equalTo(44)
            frame.left.equalToSuperview()
            frame.top.equalToSuperview().offset(statusBarHeight)
        }
        
        navigationView.addSubview(naviBackImg)
        naviBackImg.isUserInteractionEnabled = true
        naviBackImg.image = UIImage.init(named: "back_arrow_black")
        naviBackImg.snp.makeConstraints { (frame) in
            frame.leftMargin.equalToSuperview().offset(kFitWidth(24))
            frame.centerY.equalTo(statusBarHeight + 22)
            frame.width.equalTo(kFitWidth(19))
            frame.height.equalTo(kFitWidth(19))
        }
        let backTap = UITapGestureRecognizer()
        backTap.addTarget(self, action: #selector(backTapAction))
        naviBackImg.addGestureRecognizer(backTap)
   }

    @objc func backTapAction(){
        if (self.navigationController != nil) {
            self.navigationController?.popViewController(animated: true)
        }else{
            self.dismiss(animated: true) {
            }
        }
    }

    @objc func singleTapAction(){
        self.view.resignFirstResponder()
    }
    
    func presentAlertVc(confirmBtn:String, message:String, title:String, cancelBtn:String?, handler:@escaping(UIAlertAction) ->Void, viewController:UIViewController) {
        let alertVc = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: confirmBtn, style: .default, handler: { (action)in
              handler(action)
        })
        alertVc.addAction(okAction)
        if cancelBtn != nil{
            let cancelAction = UIAlertAction(title: cancelBtn, style: .cancel, handler:nil)
            alertVc.addAction(cancelAction)
        }
        viewController.present(alertVc, animated:true, completion:nil)
    }
    
    func presentAlertVcNoAction(title:String, viewController:UIViewController) {
        let alertVc = UIAlertController(title: title, message: "", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler:nil)
        alertVc.addAction(cancelAction)
        
        viewController.present(alertVc, animated:true, completion:nil)
    }
    
    func getWidthOfString(string:String,font:UIFont,height:CGFloat) -> CGFloat {
        let dict = NSDictionary.init(object: font, forKey: NSAttributedString.Key.font as NSCopying)
        
        let rect = (string as NSString).boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: height), options: [.truncatesLastVisibleLine,.usesLineFragmentOrigin,.usesFontLeading], attributes: dict as! [NSAttributedString.Key : Any], context: nil) as CGRect
        
        
        return rect.size.width
    }
    
    func getHeightOfString(string:String,font:UIFont,width:CGFloat) -> CGFloat {
        let dict = NSDictionary.init(object: font, forKey: NSAttributedString.Key.font as NSCopying)
        
        let rect = (string as NSString).boundingRect(with: CGSize.init(width: width, height: CGFloat.greatestFiniteMagnitude), options: [.truncatesLastVisibleLine,.usesLineFragmentOrigin,.usesFontLeading], attributes: dict as! [NSAttributedString.Key : Any], context: nil) as CGRect
        
        
        return rect.size.height
    }
    
    func changeRootVCToLogin() {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let newRootVC = LoginVC()
        appDelegate.switchRootViewController(to: newRootVC)
    }
    
    //MARK: - 判断是否为手机号
    func judgePhoneNumber (phoneNum:String?) -> Bool {
        let patternTemp = "^1[0-9]{10}$"
        if NSPredicate(format: "SELF MATCHES %@", patternTemp).evaluate(with: phoneNum) {
            return true
        }
        return false
    }
    func judgeEmail(email:String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
            
        do {
            let regex = try NSRegularExpression(pattern: emailRegex)
            
            if regex.matches(in: email, range: NSRange(location: 0, length: email.count)).isEmpty == false {
                return true
            } else {
                return false
            }
        } catch {
            print("Error creating regular expression")
            return false
        }
    }
    //是否需要登录
    func isNeedLogin() -> Bool{
        
        return false
    }
    //是否安装云闪付
    func isInstallYSF() -> Bool {
        return isInstallation(urlString: "upwallet://")
    }
    
    //是否安装APP
    func isInstallation(urlString:String?) -> Bool {
        let url = URL(string: urlString!)
        if url == nil {
            return false
        }
        if UIApplication.shared.canOpenURL(url!) {
            return true
        }
        return false
    }
    //MARK: - 限制手机输入11位
    @objc func phoneTextDidChange(sender:UITextField) {
        guard let _:UITextRange = sender.markedTextRange else {
            if (sender.text!as NSString).length > 11 {
                sender.text = (sender.text!as NSString).substring(to: 11)
            }
            return
        }
    }
    //JSONString转换为字典
    func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
        let jsonData:Data = jsonString.data(using: .utf8)!
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    //JSONString转换为数组
    func getArrayFromJSONString(jsonString:String) ->NSArray{
        if jsonString == "" || jsonString.isBlank{
            return []
        }
//        DLLog(message: "jsonString : \(jsonString)")
        let jsonData:Data = jsonString.data(using: .utf8)!
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if array != nil {
            return array as! NSArray
        }
        return array as! NSArray
    }
    
//    字典转换为JSONString
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
//    数组转换为JSONString
    func getJSONStringFromArray(array:NSArray) ->String{
          if !JSONSerialization.isValidJSONObject(array) {
               print("无法解析出JSONString")
               return""
          }
          let data :NSData! = try!JSONSerialization.data(withJSONObject: array, options: [])as  NSData?
          let JSONString = NSString(data: data as Data, encoding:String.Encoding.utf8.rawValue)
          return JSONString!as String
     }
    
    //导航栏高度
    func getNavigationBarHeight() -> CGFloat {
//        DLLog(message: "statusBarHeight:\(statusBarHeight)")
        return statusBarHeight + 44
    }
    //tabbar高度
    func getTabbarHeight() -> CGFloat {
        return getBottomSafeAreaHeight() + 49
//        return (statusBarHeight==44 ? 83 : 49)
    }
    //顶部的安全距离
    func getTopSafeAreaHeight() -> CGFloat {
        var topPadding = CGFloat(0)
        
        if #available(iOS 11.0, *) {
            let window = UIApplication.shared.keyWindow
            topPadding = window?.safeAreaInsets.top ?? 0
        } else {
            // Fallback on earlier versions
        }
        return topPadding
//      return (statusBarHeight - 20)
    }
    //底部的安全距离
    func getBottomSafeAreaHeight() -> CGFloat {
        var bottomPadding = CGFloat(0)
        
        if #available(iOS 11.0, *) {
            let window = UIApplication.shared.keyWindow
            bottomPadding = window?.safeAreaInsets.bottom ?? 0
        } else {
            // Fallback on earlier versions
        }
        return bottomPadding
//        return (getTabbarHeight() - 49)
    }
    func openUrl(urlString:String){
        if let url = URL(string: urlString) {
            //根据iOS系统版本，分别处理
            if #available(iOS 10, *) {
                UIApplication.shared.open(url, options: [:],
                                          completionHandler: {
                                            (success) in
                })
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    func openURL(url:URL){
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:],
                                      completionHandler: {
                                        (success) in
            })
        } else {
            UIApplication.shared.openURL(url)
        }
    }
    func getCurrentController() -> UIViewController? {
           guard let window = UIApplication.shared.windows.first else {
               return nil
           }
           var tempView: UIView?
           for subview in window.subviews.reversed() {
               if subview.classForCoder.description() == "UILayoutContainerView" {
                   tempView = subview
                   break
               }
           }
           
           if tempView == nil {
               tempView = window.subviews.last
           }
           
           var nextResponder = tempView?.next
           var next: Bool {
               return !(nextResponder is UIViewController) || nextResponder is UINavigationController || nextResponder is UITabBarController
           }

           while next{
               tempView = tempView?.subviews.first
               if tempView == nil {
                   return nil
               }
               nextResponder = tempView!.next
           }
           return nextResponder as? UIViewController
       }
}


extension WHBaseViewVC{
    func initNavi(titleStr:String,naviBgColor:UIColor? = .white,isWhite:Bool? = false){
        let naviView = UIView()
        view.addSubview(naviView)
        naviView.backgroundColor = naviBgColor
        naviView.isUserInteractionEnabled = true
        naviView.snp.makeConstraints { (frame) in
            frame.width.equalToSuperview()
            frame.height.equalTo(getNavigationBarHeight())
        }
        
        navigationView = naviView
        
        let bottomGap = 22 - kFitWidth(16)
        
        let backArrowImg = UIImageView()
    
        naviView.addSubview(backArrowImg)
        
        backArrowImg.snp.makeConstraints { (frame) in
            frame.width.equalTo(kFitWidth(30))
            frame.height.equalTo(kFitWidth(30))
            frame.left.equalTo(kFitWidth(10))
            frame.bottom.equalToSuperview().offset(-bottomGap)
        }
        backArrowImg.isUserInteractionEnabled = true
        naviBackImg = backArrowImg
        
        let backView = UIView()
        backView.backgroundColor = .clear
        naviView.addSubview(backView)
        backView.isUserInteractionEnabled = true
        backView.snp.makeConstraints { (frame) in
            frame.width.height.equalTo(kFitWidth(50))
            frame.center.lessThanOrEqualTo(backArrowImg.snp_center)
        }
        
        let backArrowTap = UITapGestureRecognizer()
        backArrowTap.addTarget(self, action: #selector(backTapAction))
        backView.addGestureRecognizer(backArrowTap)
        
        let titleLabel = UILabel()
        naviView.addSubview(titleLabel)
        titleLabel.text = titleStr
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 18)
        titleLabel.snp.makeConstraints { (frame) in
            frame.centerY.equalTo(backArrowImg)
//            frame.left.equalTo(backArrowImg.snp.right).offset(kFitWidth(30))
            frame.centerX.lessThanOrEqualToSuperview()
        }
        naviTitleLabel = titleLabel
        
        if isWhite ?? false {
            backArrowImg.image = UIImage.init(named: "back_arrow_white")
            titleLabel.textColor = .white
        }else{
            backArrowImg.image = UIImage.init(named: "back_arrow_black")
            titleLabel.textColor = WHColor_TextBlack()
        }
    }
    
    func createVCObjectFromString(className:String) -> UIViewController{
        let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String
        let classType:AnyClass? = NSClassFromString(nameSpace! + "." + className)
        let viewController = classType as! UIViewController.Type
        
        return viewController.init()
    }
    
    func isPurnInt(string: String) -> Bool {
        let scan: Scanner = Scanner(string: string)

        var val:Int = 0

        return scan.scanInt(&val) && scan.isAtEnd

    }
    
}

extension WHBaseViewVC{
//    func sendPolicyRequest() {
//        WHNetworkUtil.shareManager().GET(urlString: URL_OSS_policy, vc: self, authori: "2") { responseObject in
//            DLLog(message: "\(responseObject)")
//            UserModel.shared.updateOssMsg(ossInfo: responseObject["data"]as? NSDictionary ?? [:])
//        }
//    }
    func sendUserCenterRequest() {
        WHNetworkUtil.shareManager().GET(urlString: URL_User_Center, vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            
            UserModel.shared.updateUserInfo(userInfo: responseObject["data"]as? NSDictionary ?? [:])
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshUserInfo") , object: nil)
        }
    }
}

extension WHBaseViewVC{
    func iphoneType() ->String {
           var systemInfo = utsname()
           uname(&systemInfo)
           
           let platform = withUnsafePointer(to: &systemInfo.machine.0) { ptr in
                   return String(cString: ptr)
               }
    
           if platform == "iPhone1,1" { return "iPhone 2G"}
           if platform == "iPhone1,2" { return "iPhone 3G"}
           if platform == "iPhone2,1" { return "iPhone 3GS"}
           if platform == "iPhone3,1" { return "iPhone 4"}
           if platform == "iPhone3,2" { return "iPhone 4"}
           if platform == "iPhone3,3" { return "iPhone 4"}
           if platform == "iPhone4,1" { return "iPhone 4S"}
           if platform == "iPhone5,1" { return "iPhone 5"}
           if platform == "iPhone5,2" { return "iPhone 5"}
           if platform == "iPhone5,3" { return "iPhone 5C"}
           if platform == "iPhone5,4" { return "iPhone 5C"}
           if platform == "iPhone6,1" { return "iPhone 5S"}
           if platform == "iPhone6,2" { return "iPhone 5S"}
           if platform == "iPhone7,1" { return "iPhone 6 Plus"}
           if platform == "iPhone7,2" { return "iPhone 6"}
           if platform == "iPhone8,1" { return "iPhone 6S"}
           if platform == "iPhone8,2" { return "iPhone 6S Plus"}
           if platform == "iPhone8,4" { return "iPhone SE"}
           if platform == "iPhone9,1" { return "iPhone 7"}
           if platform == "iPhone9,2" { return "iPhone 7 Plus"}
           if platform == "iPhone10,1" { return "iPhone 8"}
           if platform == "iPhone10,2" { return "iPhone 8 Plus"}
           if platform == "iPhone10,3" { return "iPhone X"}
           if platform == "iPhone10,4" { return "iPhone 8"}
           if platform == "iPhone10,5" { return "iPhone 8 Plus"}
           if platform == "iPhone10,6" { return "iPhone X"}
           if platform == "iPhone11,2" { return "iPhone XS"}
           if platform == "iPhone11,4" { return "iPhone XS MAX(China)"}
           if platform == "iPhone11,6" { return "iPhone XS MAX"}
           if platform == "iPhone11,8" { return "iPhone XR"}
        
        
            if platform == "iPhone12,1" { return "iPhone 11"}
            if platform == "iPhone12,3" { return "iPhone 11 Pro"}
            if platform == "iPhone12,5" { return "iPhone 11 Pro Max"}
            if platform == "iPhone12,8" { return "iPhone SE 2nd Gen"}
            if platform == "iPhone13,1" { return "iPhone 12 mini"}
            if platform == "iPhone13,2" { return "iPhone 12"}
            if platform == "iPhone13,3" { return "iPhone 12 Pro"}
            if platform == "iPhone13,4" { return "iPhone 12 Pro Max"}
            if platform == "iPhone14,4" { return "iPhone 13 mini"}
            if platform == "iPhone14,5" { return "iPhone 13"}
            if platform == "iPhone14,2" { return "iPhone 13 Pro"}
            if platform == "iPhone14,3" { return "iPhone 12 Pro Max"}
           
           if platform == "iPod1,1" { return "iPod Touch 1G"}
           if platform == "iPod2,1" { return "iPod Touch 2G"}
           if platform == "iPod3,1" { return "iPod Touch 3G"}
           if platform == "iPod4,1" { return "iPod Touch 4G"}
           if platform == "iPod5,1" { return "iPod Touch 5G"}
           
           if platform == "iPad1,1" { return "iPad 1"}
           if platform == "iPad2,1" { return "iPad 2"}
           if platform == "iPad2,2" { return "iPad 2"}
           if platform == "iPad2,3" { return "iPad 2"}
           if platform == "iPad2,4" { return "iPad 2"}
           if platform == "iPad2,5" { return "iPad Mini 1"}
           if platform == "iPad2,6" { return "iPad Mini 1"}
           if platform == "iPad2,7" { return "iPad Mini 1"}
           if platform == "iPad3,1" { return "iPad 3"}
           if platform == "iPad3,2" { return "iPad 3"}
           if platform == "iPad3,3" { return "iPad 3"}
           if platform == "iPad3,4" { return "iPad 4"}
           if platform == "iPad3,5" { return "iPad 4"}
           if platform == "iPad3,6" { return "iPad 4"}
           if platform == "iPad4,1" { return "iPad Air"}
           if platform == "iPad4,2" { return "iPad Air"}
           if platform == "iPad4,3" { return "iPad Air"}
           if platform == "iPad4,4" { return "iPad Mini 2"}
           if platform == "iPad4,5" { return "iPad Mini 2"}
           if platform == "iPad4,6" { return "iPad Mini 2"}
           if platform == "iPad4,7" { return "iPad Mini 3"}
           if platform == "iPad4,8" { return "iPad Mini 3"}
           if platform == "iPad4,9" { return "iPad Mini 3"}
           if platform == "iPad5,1" { return "iPad Mini 4"}
           if platform == "iPad5,2" { return "iPad Mini 4"}
           if platform == "iPad5,3" { return "iPad Air 2"}
           if platform == "iPad5,4" { return "iPad Air 2"}
           if platform == "iPad6,3" { return "iPad Pro 9.7"}
           if platform == "iPad6,4" { return "iPad Pro 9.7"}
           if platform == "iPad6,7" { return "iPad Pro 12.9"}
           if platform == "iPad6,8" { return "iPad Pro 12.9"}
           
           if platform == "i386"   { return "iPhone Simulator"}
           if platform == "x86_64" { return "iPhone Simulator"}
           
           return "NEW iPhone"
       }
}
